package com.geeyuu.android.activity;

import java.io.File;
import java.lang.ref.WeakReference;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.customview.wheel.AbstractWheelTextAdapter;
import com.geeyuu.android.customview.wheel.OnWheelChangedListener;
import com.geeyuu.android.customview.wheel.WheelView;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.HttpUtil;
import com.geeyuu.android.utils.ImageLoder;
import com.geeyuu.android.utils.LogUtil;
import com.geeyuu.android.utils.HttpUtil.HttpUploadListener;

public class Activity4 extends BaseActivity {

    private long uid;
    private BaseUserInfo myUserInfo;
    private ImageLoder mImageLoder;
    private MyHandler mHandler;
    private int width;
    private int dip5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "Activity4";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity4_layout);

        uid = GeePrefrence.getMyUid(getApplicationContext());
        myUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
        mImageLoder = new ImageLoder(getApplicationContext());
        mHandler = new MyHandler(this);

        dip5 = AndroidUtil.dip2px(getApplicationContext(), 5);
        width = ((mImageLoder.screenWidth - AndroidUtil.dip2px(getApplicationContext(), 25)) / 7) * 2 + dip5;

        initTitleViews();
        initContentViews();

        startBindService();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PhotoBrowserActivity.isNeedRefresh) {
            LogUtil.i(TAG, "设置了头像或者删除了照片，需要重新更新UI");
            PhotoBrowserActivity.isNeedRefresh = false;
            myUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
            LogUtil.i(TAG, "公开:" + myUserInfo.publicPhotoIds);
            LogUtil.i(TAG, "私照:" + myUserInfo.privatePhotoIds);
            initUserBaseInfoView();
            initPublicPhotoViews();
            initPrivatePhotoViews();
        }
    }

    private String myNickName;
    private String myRole;
    private String myAge;
    private String myHeight;
    private String myWeight;
    private String mySign;
    private boolean isChanged = false;

    @Override
    protected void onPause() {
        super.onPause();
        if (isChanged) { // 发送更新
            Bundle bundle = new Bundle();
            bundle.putString(DataKey.S_KEY_USERINFO_NICKNAME, myNickName);
            bundle.putString(DataKey.S_KEY_USERINFO_AGE, myAge);
            bundle.putString(DataKey.S_KEY_USERINFO_HEIGHT, myHeight);
            bundle.putString(DataKey.S_KEY_USERINFO_WEIGHT, myWeight);
            bundle.putString(DataKey.S_KEY_USERINFO_ROLE, myRole);
            bundle.putString(DataKey.S_KEY_USERINFO_SIGN, mySign);
            sendMsgToService(ProtocolCommand.CMD_SET_MY_USER_INFO, bundle);
        }
    }

    private void sendQueryAlbumCmd(String type) {
        Bundle bundle = new Bundle();
        bundle.putString(DataKey.S_KEY_USER_PHOTO_QUERY_UID, String.valueOf(uid));
        bundle.putString(DataKey.S_KEY_USER_PHOTO_QUERY_PAGE_INDEX, "0");
        bundle.putString(DataKey.S_KEY_USER_PHOTO_QUERY_TYPE, type);
        sendMsgToService(ProtocolCommand.CMD_QUERY_ALBUM, bundle);
    }

    private ProgressBar pubProgress;
    private ProgressBar priProgress;
    private ProgressBar baseInfoProgress;

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {

        switch (cmd) {
        case ProtocolCommand.CMD_QUERY_USER_INFO:
            if (isMsgNormal) {
                BaseUserInfo nowUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);

                if (GeePrefrence.getIsFirst(getApplicationContext())) {
                    GeePrefrence.setIsFirst(getApplicationContext(), false);
                    sendQueryAlbumCmd(DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC);
                    if (pubProgress == null) {
                        pubProgress = (ProgressBar) findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.VISIBLE);
                } else {
                    if (nowUserInfo.lastAlbumModifyTime != myUserInfo.lastAlbumModifyTime) {
                        sendQueryAlbumCmd(DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC);
                        if (pubProgress == null) {
                            pubProgress = (ProgressBar) findViewById(R.id.load_pub_progress);
                        }
                        pubProgress.setVisibility(View.VISIBLE);
                    }
                }

                myUserInfo = nowUserInfo;
                mHandler.sendEmptyMessage(0);
            } else {
                AndroidUtil.showToast(getApplicationContext(), "读取网络数据失败");
            }
            if (baseInfoProgress == null) {
                baseInfoProgress = (ProgressBar) findViewById(R.id.load_baseinfo_progress);
            }
            baseInfoProgress.setVisibility(View.GONE);
            break;

        case ProtocolCommand.CMD_QUERY_ALBUM:
            int photoType = bundle.getInt("photoType");
            if (isMsgNormal) {
                myUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
                if (photoType == 1) { // pub

                    if (pubProgress == null) {
                        pubProgress = (ProgressBar) findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.GONE);

                    if (priProgress == null) {
                        priProgress = (ProgressBar) findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.VISIBLE);

                    LogUtil.d(TAG, "更新公开相册");
                    mHandler.sendEmptyMessage(1);
                    sendQueryAlbumCmd(DataKey.S_VALUE_USER_PHOTO_TYPE_PRIVATE);
                } else if (photoType == 2) { // pri

                    if (priProgress == null) {
                        priProgress = (ProgressBar) findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.GONE);

                    LogUtil.d(TAG, "更新私密相册");
                    mHandler.sendEmptyMessage(2);
                } else {
                    LogUtil.e(TAG, "逻辑错误 unknow photoType: " + photoType);
                }
            } else {
                if (photoType == 1) {
                    if (pubProgress == null) {
                        pubProgress = (ProgressBar) findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.GONE);
                } else if (photoType == 2) {
                    if (priProgress == null) {
                        priProgress = (ProgressBar) findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.GONE);
                }
                AndroidUtil.showToast(getApplicationContext(), "读取网络数据失败");
            }
            break;

        case ProtocolCommand.CMD_ADD_TO_ALBUM:
            if (isMsgNormal) {
                cancelProgressDialog();
                myUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
                if (type == 1) {
                    mHandler.sendEmptyMessage(1);
                } else if (type == 2) {
                    mHandler.sendEmptyMessage(2);
                }
            } else {
                cancelProgressDialog();
                AndroidUtil.showMyToast(getApplicationContext(), "添加照片失败");
            }
            break;
        }

    }

    @Override
    protected void onConnectServiceCallBack() {
        Bundle bundle = new Bundle();
        bundle.putString(DataKey.S_KEY_QUERY_USER_INFO_UID, String.valueOf(uid));
        sendMsgToService(ProtocolCommand.CMD_QUERY_USER_INFO, bundle);
    }

    private void initUserBaseInfoView() {
        ImageView avatarImageView = (ImageView) findViewById(R.id.my_profile_avatar);
        mImageLoder.add(myUserInfo.mainPhotoID, avatarImageView, true);

        TextView popValue = (TextView) findViewById(R.id.flower);
        popValue.setText("X " + myUserInfo.popValue);

        TextView money = (TextView) findViewById(R.id.gold_coin);
        money.setText("X " + myUserInfo.money);

        TextView myAttention = (TextView) findViewById(R.id.my_attention_textview);
        TextView myFans = (TextView) findViewById(R.id.my_fans_num_textview);
        TextView myVisitor = (TextView) findViewById(R.id.my_visitor_textview);

        String myattentionList = GeePrefrence.getAttentionList(getApplicationContext());
        String myfansList = GeePrefrence.getMyFansList(getApplicationContext());
        String myVisitorList = GeePrefrence.getMyVisitorList(getApplicationContext());

        if (!CommonUtil.isEmpty(myattentionList)) {
            String[] attentionArray = myattentionList.split(",");
            if (null != attentionArray) {
                myAttention.setText(attentionArray.length + "");
            } else {
                myAttention.setText("0");
            }
        } else {
            myAttention.setText("0");
        }
        if (!CommonUtil.isEmpty(myfansList)) {
            String[] fansArray = myfansList.split(",");
            if (null != fansArray) {
                myFans.setText(fansArray.length + "");
            } else {
                myFans.setText("0");
            }
        } else {
            myFans.setText("0");
        }
        if (!CommonUtil.isEmpty(myVisitorList)) {
            String[] visitorsArray = myVisitorList.split(",");
            if (null != visitorsArray) {
                myVisitor.setText(visitorsArray.length + "");
            } else {
                myVisitor.setText("0");
            }
        } else {
            myVisitor.setText("0");
        }

        myNickNameTextView.setText(myUserInfo.nickName);
        myRoleTextView.setText(myUserInfo.getRealRole());
    }

    private void initHideUserBaseInfo() {
        if (userBaseInfoView != null) {
            myAgeTextView = (TextView) userBaseInfoView.findViewById(R.id.profile_age_textview);
            myAgeTextView.setText(myUserInfo.age + "");
            myAgeTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.edit_icon, 0);
            myAgeTextView.setOnClickListener(mOnClickListener);

            myHeightTextView = (TextView) userBaseInfoView.findViewById(R.id.profile_height_textview);
            myHeightTextView.setText(myUserInfo.height + " cm");
            myHeightTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.edit_icon, 0);
            myHeightTextView.setOnClickListener(mOnClickListener);

            myWeightTextView = (TextView) userBaseInfoView.findViewById(R.id.profile_weight_textview);
            myWeightTextView.setText(myUserInfo.weight + " kg");
            myWeightTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.edit_icon, 0);
            myWeightTextView.setOnClickListener(mOnClickListener);

            mySignTextView = (TextView) userBaseInfoView.findViewById(R.id.profile_sign_textview);
            mySignTextView.setText(myUserInfo.sign);
            mySignTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.edit_icon, 0);
            mySignTextView.setOnClickListener(mOnClickListener);
        }
    }

    private OnClickListener photoClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int index = (Integer) v.getTag();
            int type = (Integer) v.getTag(R.string.photo_key);
            Intent intent = new Intent(Activity4.this, PhotoBrowserActivity.class);
            intent.putExtra("index", index);
            intent.putExtra("type", type);
            intent.putExtra("uid", uid);
            if (null != publicPhotoIdsArray) {
                intent.putExtra("publicPhotoIds", publicPhotoIdsArray);
            }
            if (null != privatePhotoIdsArray) {
                intent.putExtra("privatePhotoIds", privatePhotoIdsArray);
            }
            startActivity(intent);
        }
    };

    private TextView publicCount;
    private LinearLayout publicPhotoContainer;
    private String[] publicPhotoIdsArray;

    private TextView privateCount;
    private LinearLayout privatePhotoContainer;
    private String[] privatePhotoIdsArray;

    private void initPublicPhotoViews() {
        String publicPhotoIds = myUserInfo.publicPhotoIds;
        if (!CommonUtil.isEmpty(publicPhotoIds)) {
            publicPhotoIdsArray = publicPhotoIds.split(",");
            if (publicPhotoIdsArray != null && publicPhotoIdsArray.length > 0) {
                if (null == publicCount) {
                    publicCount = (TextView) findViewById(R.id.public_photo_title);
                }
                publicCount.setText("公开相册(" + publicPhotoIdsArray.length + "/10)");
                if (null == publicPhotoContainer) {
                    publicPhotoContainer = (LinearLayout) findViewById(R.id.public_photo_container);
                }
                publicPhotoContainer.removeAllViews();
                int indexTag = 0;
                for (String photoId : publicPhotoIdsArray) {
                    ImageView imageView = new ImageView(this);
                    imageView.setScaleType(ScaleType.FIT_XY);
                    imageView.setOnClickListener(photoClick);
                    imageView.setTag(indexTag);
                    imageView.setTag(R.string.photo_key, 0);
                    imageView.setPadding(dip5, 0, 0, 0);
                    ViewGroup.LayoutParams vl = new ViewGroup.LayoutParams(width, width);
                    imageView.setLayoutParams(vl);
                    publicPhotoContainer.addView(imageView);
                    mImageLoder.add(photoId, imageView, true);
                    indexTag++;
                }
            } else {
                if (null == publicPhotoContainer) {
                    publicPhotoContainer = (LinearLayout) findViewById(R.id.public_photo_container);
                }
                publicPhotoContainer.removeAllViews();
            }
        } else {
            if (null == publicPhotoContainer) {
                publicPhotoContainer = (LinearLayout) findViewById(R.id.public_photo_container);
            }
            publicPhotoContainer.removeAllViews();
        }
    }

    private void initPrivatePhotoViews() {
        String privatePhotoIds = myUserInfo.privatePhotoIds;
        if (!CommonUtil.isEmpty(privatePhotoIds)) {
            privatePhotoIdsArray = privatePhotoIds.split(",");
            if (privatePhotoIdsArray != null && privatePhotoIdsArray.length > 0) {
                if (privateCount == null) {
                    privateCount = (TextView) findViewById(R.id.private_photo_title);
                }
                privateCount.setText("私密相册(" + privatePhotoIdsArray.length + "/10)");
                if (privatePhotoContainer == null) {
                    privatePhotoContainer = (LinearLayout) findViewById(R.id.private_photo_container);
                }
                privatePhotoContainer.removeAllViews();
                int indexTag = 0;
                for (String photoId : privatePhotoIdsArray) {
                    ImageView imageView = new ImageView(this);
                    imageView.setScaleType(ScaleType.FIT_XY);
                    imageView.setOnClickListener(photoClick);
                    imageView.setTag(indexTag);
                    imageView.setTag(R.string.photo_key, 1);
                    imageView.setPadding(dip5, 0, 0, 0);
                    ViewGroup.LayoutParams vl = new ViewGroup.LayoutParams(width, width);
                    imageView.setLayoutParams(vl);
                    privatePhotoContainer.addView(imageView);
                    mImageLoder.add(photoId, imageView, true);
                    indexTag++;
                }
            } else {
                if (privatePhotoContainer == null) {
                    privatePhotoContainer = (LinearLayout) findViewById(R.id.private_photo_container);
                }
                privatePhotoContainer.removeAllViews();
            }
        } else {
            if (privatePhotoContainer == null) {
                privatePhotoContainer = (LinearLayout) findViewById(R.id.private_photo_container);
            }
            privatePhotoContainer.removeAllViews();
        }
    }

    private void initTitleViews() {
        Button topLeftButton = (Button) findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setText("个人");
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.title_icon_tab4, 0, 0, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 10), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if (null == vl) {
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        } else {
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);

        Button topRight = (Button) findViewById(R.id.top_right_button);
        topRight.setText("设置");
        topRight.setVisibility(View.VISIBLE);
        topRight.setOnClickListener(mOnClickListener);
    }

    private WheelView wheelView;
    private MyWheelAdapter myWheelAdapter;
    private View wheelViewContainer;
    private int currentWheelItemIndex;
    private int currentButtonChoice;
    private PopupWindow popupWindow;
    private View anchor = null;
    private ScrollView scrollView;

    private TextView myNickNameTextView;
    private TextView myRoleTextView;
    private TextView myAgeTextView;
    private TextView myHeightTextView;
    private TextView myWeightTextView;
    private TextView mySignTextView;

    private void initContentViews() {

        viewStub = (ViewStub) findViewById(R.id.more_info_container);
        clickTips = (TextView) findViewById(R.id.show_more_info_button);
        clickTips.setOnClickListener(mOnClickListener);
        clickTips2 = (TextView) findViewById(R.id.show_more_info_button2);
        clickTips2.setOnClickListener(mOnClickListener);

        myNickNameTextView = (TextView) findViewById(R.id.my_nick_name);
        myNickNameTextView.setOnClickListener(mOnClickListener);
        myRoleTextView = (TextView) findViewById(R.id.my_role);
        myRoleTextView.setOnClickListener(mOnClickListener);

        findViewById(R.id.attention_me_view_container).setOnClickListener(mOnClickListener);
        findViewById(R.id.my_attention_view_container).setOnClickListener(mOnClickListener);
        findViewById(R.id.looked_me_view_container).setOnClickListener(mOnClickListener);

        scrollView = (ScrollView) findViewById(R.id.scrollview);
        wheelViewContainer = getLayoutInflater().inflate(R.layout.register_baseinfo_popup_layout,
                (ViewGroup) findViewById(R.id.all_container), false);
        Button comfire = (Button) wheelViewContainer.findViewById(R.id.comfire);
        comfire.setOnClickListener(mOnClickListener);
        Button cancel = (Button) wheelViewContainer.findViewById(R.id.cancel);
        cancel.setOnClickListener(mOnClickListener);
        wheelView = (WheelView) wheelViewContainer.findViewById(R.id.wheel_view);
        wheelView.setVisibleItems(3);
        wheelView.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                currentWheelItemIndex = newValue;
            }
        });
        popupWindow = new PopupWindow(wheelViewContainer, WindowManager.LayoutParams.FILL_PARENT,
                WindowManager.LayoutParams.FILL_PARENT);
        myWheelAdapter = new MyWheelAdapter(this);

        View v1 = findViewById(R.id.add_pub_photo_button);
        ViewGroup.LayoutParams vl1 = v1.getLayoutParams();
        if (null == vl1) {
            vl1 = new ViewGroup.LayoutParams(width, width);
        } else {
            vl1.width = width;
            vl1.height = width;
        }
        v1.setLayoutParams(vl1);
        v1.setOnClickListener(mOnClickListener);

        View v2 = findViewById(R.id.add_pri_photo_button);
        ViewGroup.LayoutParams vl2 = v2.getLayoutParams();
        if (null == vl2) {
            vl2 = new ViewGroup.LayoutParams(width, width);
        } else {
            vl2.width = width;
            vl2.height = width;
        }
        v2.setLayoutParams(vl2);
        v2.setOnClickListener(mOnClickListener);

        initUserBaseInfoView();
        initPublicPhotoViews();
        initPrivatePhotoViews();

    }

    private String[] ages = null;
    private String[] heights = null;
    private String[] weights = null;
    private static final String[] roles = { "保密", "0", "1", "0.5" };

    private void initRoleWheelView() {
        currentButtonChoice = 0;
        showWheelView(roles, 1);
    }

    private void initAgeWheelView() {
        if (null == ages) {
            ages = new String[83];
            for (int i = 17; i < 100; i++) {
                ages[i - 17] = String.valueOf(i);
            }
        }
        currentButtonChoice = 1;
        showWheelView(ages, 8);
    }

    private void initHeightWheelView() {
        if (null == heights) {
            heights = new String[110];
            for (int i = 140; i < 250; i++) {
                heights[i - 140] = String.valueOf(i) + " cm";
            }
        }
        currentButtonChoice = 2;
        showWheelView(heights, 30);
    }

    private void initWeightWheelView() {
        if (null == weights) {
            weights = new String[210];
            for (int i = 40; i < 250; i++) {
                weights[i - 40] = String.valueOf(i) + " kg";
            }
        }
        currentButtonChoice = 3;
        showWheelView(weights, 80);
    }

    private void showWheelView(String[] param, int initIndex) {
        myWheelAdapter.setItemData(param);
        wheelView.setViewAdapter(myWheelAdapter);
        wheelView.setCurrentItem(initIndex);

        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.showAsDropDown(anchor);
    }

    private class MyWheelAdapter extends AbstractWheelTextAdapter {
        private String[] data;

        protected MyWheelAdapter(Context context) {
            super(context, R.layout.wheel_item_layout, R.id.wheel_item_text);
        }

        public void setItemData(String[] param) {
            data = param;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return data.length;
        }

        @Override
        protected CharSequence getItemText(int index) {
            return data[index];
        }
    }

    private ViewStub viewStub;
    private View userBaseInfoView;
    private TextView clickTips;
    private TextView clickTips2;
    private boolean isMoreBaseInfoShowing = false;

    private void setHideViews() {
        isMoreBaseInfoShowing = !isMoreBaseInfoShowing;
        if (isMoreBaseInfoShowing) {
            if (viewStub != null && userBaseInfoView == null) {
                userBaseInfoView = viewStub.inflate();
                initHideUserBaseInfo();
            } else {
                userBaseInfoView.setVisibility(View.VISIBLE);
            }
            clickTips.setBackgroundResource(R.drawable.click_up);
            clickTips2.setText("点击收起");
        } else {
            if (null != userBaseInfoView) {
                userBaseInfoView.setVisibility(View.GONE);
            }
            clickTips.setBackgroundResource(R.drawable.click_down);
            clickTips2.setText("点击展开");
        }
    }

    private static class MyHandler extends Handler {
        private final WeakReference<Activity4> activity4;

        public MyHandler(Context context) {
            activity4 = new WeakReference<Activity4>((Activity4) context);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                activity4.get().initUserBaseInfoView();
                activity4.get().initHideUserBaseInfo();
                break;
            case 1:
                activity4.get().initPublicPhotoViews();
                break;
            case 2:
                activity4.get().initPrivatePhotoViews();
                break;
            case 3:
                final int type = msg.arg1;
                activity4.get().type = type;
                final String photoId = (String) msg.obj;

                Bundle bundle = new Bundle();
                if (type == 1) {
                    bundle.putString(DataKey.S_KEY_PHOTO_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC);
                } else if (type == 2) {
                    bundle.putString(DataKey.S_KEY_PHOTO_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PRIVATE);
                }
                bundle.putString(DataKey.S_KEY_PHOTO_ACTION, DataKey.S_VALUE_ACTION_ADD);
                bundle.putString(DataKey.S_KEY_PHOTO_ID, photoId);
                activity4.get().sendMsgToService(ProtocolCommand.CMD_ADD_TO_ALBUM, bundle);

                break;
            case 4:
                activity4.get().cancelProgressDialog();
                AndroidUtil.showMyToast(activity4.get().getApplicationContext(), "上传照片失败");
                break;
            }
        }
    }

    private int type = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 55) {
            if (resultCode == 99) {
                final String filePath = data.getStringExtra("filePath");
                final int type = data.getIntExtra("type", -1);

                if (CommonUtil.isEmpty(filePath) || type < 0) {
                    AndroidUtil.showMyToast(getApplicationContext(), "获取照片失败");
                    return;
                }

                LogUtil.d(TAG, "filePath: " + filePath);

                final File photoFile = new File(filePath);
                if (photoFile.exists() && photoFile.length() > 0) {
                    showProgressDialog("上传照片", "正在上传照片，请稍等..", false);
                    HttpUtil.postFileForString(GeeConstants.IMG_UPLOAD_HTTP_URL, photoFile, 3, 3000,
                            new HttpUploadListener() {
                                @Override
                                public void onUploadFinish(final String returnFileId) {
                                    LogUtil.i(TAG, "上传照片成功");

                                    if (!photoFile
                                            .renameTo(new File(GeeConstants.PATH_LARGE_IMAGE_FOLDER, returnFileId))) {
                                        LogUtil.e(TAG, "临时照片名字改名为正式名字失败！");
                                    }

                                    File thumbFile = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, "small_photo_temp");
                                    if (!thumbFile
                                            .renameTo(new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, returnFileId))) {
                                        LogUtil.e(TAG, "临时小照片名字改名为正式名字失败！");
                                    }

                                    ContentValues cv = new ContentValues();
                                    cv.put("uid", uid);
                                    String photoIds;
                                    if (type == 1) {
                                        photoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(),
                                                uid, BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS);
                                        if (photoIds != null && photoIds.trim().length() > 0) {
                                            photoIds = photoIds + "," + returnFileId;
                                        } else {
                                            photoIds = returnFileId;
                                        }
                                        cv.put(BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS, photoIds);
                                    } else if (type == 2) {
                                        photoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(),
                                                uid, BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS);
                                        if (photoIds != null && photoIds.trim().length() > 0) {
                                            photoIds = photoIds + "," + returnFileId;
                                        } else {
                                            photoIds = returnFileId;
                                        }
                                        cv.put(BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS, photoIds);
                                    }
                                    BaseUserInfo.updateUserInfo(getApplicationContext(), cv);
                                    myUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
                                    mHandler.obtainMessage(3, type, 0, returnFileId).sendToTarget();
                                }

                                @Override
                                public void onUploadFail() {
                                    LogUtil.w(TAG, "上传照片失败");
                                    mHandler.sendEmptyMessage(4);
                                }
                            });
                } else {
                    LogUtil.e(TAG, "获取照片失败");
                    AndroidUtil.showMyToast(getApplicationContext(), "获取照片失败");
                }
            } else if (resultCode == 88) {
                LogUtil.e(TAG, "获取照片失败");
                 AndroidUtil.showMyToast(getApplicationContext(), "获取照片失败");
            } else {
                LogUtil.e(TAG, "未设定的结果码:" + resultCode);
//                AndroidUtil.showMyToast(getApplicationContext(), "获取照片失败");
            }
        }
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {

            case R.id.add_pub_photo_button:
                Intent addPubIntent = new Intent(getApplicationContext(), DialogActivity.class);
                addPubIntent.putExtra("type", 1);
                startActivityForResult(addPubIntent, 55);
                break;

            case R.id.add_pri_photo_button:
                Intent addPriIntent = new Intent(getApplicationContext(), DialogActivity.class);
                addPriIntent.putExtra("type", 2);
                startActivityForResult(addPriIntent, 55);
                break;

            case R.id.top_right_button:
                Intent intent = new Intent(Activity4.this, AppOptionsActivity.class);
                startActivity(intent);
                break;
            case R.id.show_more_info_button:
                setHideViews();
                break;
            case R.id.show_more_info_button2:
                setHideViews();
                break;

            // ========
            case R.id.profile_age_textview:
                anchor = v;
                scrollView.smoothScrollTo(0, v.getHeight());
                initAgeWheelView();
                break;
            case R.id.profile_height_textview:
                anchor = v;
                scrollView.smoothScrollTo(0, v.getHeight() * 2);
                initHeightWheelView();
                break;
            case R.id.profile_weight_textview:
                anchor = v;
                scrollView.smoothScrollTo(0, v.getHeight() * 3);
                initWeightWheelView();
                break;
            case R.id.profile_sign_textview:
                showSignEditDialog();
                break;
            case R.id.my_nick_name:
                showNickNameEditDialog();
                break;
            case R.id.my_role:
                anchor = v;
                scrollView.smoothScrollTo(0, 0);
                initRoleWheelView();
                break;
            case R.id.comfire:
                isChanged = true;
                if (currentButtonChoice == 0) {
                    myRoleTextView.setText(roles[currentWheelItemIndex]);
                    myRole = String.valueOf(currentWheelItemIndex);
                } else if (currentButtonChoice == 1) {
                    myAgeTextView.setText(ages[currentWheelItemIndex]);
                    myAge = ages[currentWheelItemIndex];
                } else if (currentButtonChoice == 2) {
                    myHeightTextView.setText(heights[currentWheelItemIndex]);
                    myHeight = heights[currentWheelItemIndex].replace("cm", "").trim();
                } else if (currentButtonChoice == 3) {
                    myWeightTextView.setText(weights[currentWheelItemIndex]);
                    myWeight = weights[currentWheelItemIndex].replace("kg", "").trim();
                }
                changePopWindowState();
                break;
            case R.id.cancel:
                changePopWindowState();
                break;
            // =============

            case R.id.attention_me_view_container:
                startActivity(new Intent(Activity4.this, PersonListActivity.class).putExtra(
                        PersonListActivity.EXTRA_TYPE, PersonListActivity.TYPE_ACTTENTION_ME));
                break;
            case R.id.my_attention_view_container:
                startActivity(new Intent(Activity4.this, PersonListActivity.class).putExtra(
                        PersonListActivity.EXTRA_TYPE, PersonListActivity.TYPE_MY_ATTENTION));
                break;
            case R.id.looked_me_view_container:
                startActivity(new Intent(Activity4.this, PersonListActivity.class).putExtra(
                        PersonListActivity.EXTRA_TYPE, PersonListActivity.TYPE_LOOKED_ME));
                break;
            }
        }
    };

    private void showNickNameEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("昵称");
        EditText et = new EditText(this);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                myNickName = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        builder.setView(et);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isChanged = true;
                myNickNameTextView.setText(myNickName);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    private void showSignEditDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("签名");
        EditText et = new EditText(this);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mySign = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        builder.setView(et);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isChanged = true;
                mySignTextView.setText(mySign);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    private void changePopWindowState() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            scrollView.smoothScrollTo(0, 0);
        }
    }

    @Override
    protected void onDestroy() {
        stopBindService();
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }

}
